package org.jeecg.modules.solitaire_app.app.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.solitaire_app.app.entity.AO.BinfPhoneNumber;
import org.jeecg.modules.solitaire_app.app.entity.YsySystem;
import org.jeecg.modules.solitaire_app.app.entity.YsyUsers;
import org.jeecg.modules.solitaire_app.app.mapper.WXLoginMapper;
import org.jeecg.modules.solitaire_app.app.query.UsersLoginQuery;
import org.jeecg.modules.solitaire_app.app.query.UsersPhoneQuery;
import org.jeecg.modules.solitaire_app.app.service.WXLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
@DS("ysy_db")
public class WXLoginServiceImpl implements WXLoginService {

    @Autowired
    private WXLoginMapper wxLoginMapper;
    @Autowired
    private RestTemplate restTemplate;


    private String getPhoneNumber_URI = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

    @Override
    @Transactional
    public Result<YsyUsers> webchatLogin(UsersLoginQuery cpsUsersAO) {
        Result<YsyUsers> result = new Result<>();
        //用户信息
        YsyUsers userStorage = new YsyUsers();
        //查询小程序配置
        YsySystem saSystem = wxLoginMapper.getBSystem(cpsUsersAO.getAppId());
        if (ObjectUtil.isNull(saSystem)) {
            result.setCode(500);
            result.setSuccess(false);
            result.setMessage("小程序配置未找到");
            return result;
        }
        String loginUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=" + saSystem.getAppid() + "&secret=" + saSystem.getAppsecret() + "&grant_type=authorization_code&js_code=";
        try {
            String loginResult = restTemplate.getForObject(loginUrl + cpsUsersAO.getCode(), String.class);
            YsyUsers cpsUsers = JSON.parseObject(JSON.parse(loginResult).toString(), YsyUsers.class);
            cpsUsers.setAvatarUrl(cpsUsersAO.getAvatarUrl());
            cpsUsers.setNickName(cpsUsersAO.getNickName());
            if (StringUtils.isEmpty(cpsUsers.getOpenid())) {
                result.error500("登录失败");
                return result;
            }
            YsyUsers userFlag = wxLoginMapper.getCpsUsersByOpenId(cpsUsers.getOpenid());
            if (StringUtils.isEmpty(userFlag)) {
                //新用户注册
                cpsUsers.setSuperiorCode(cpsUsersAO.getSuperiorCode());
                cpsUsers.setInvitationCode(RandomUtil.randomStringUpper(6) + "_" + RandomUtil.randomStringUpper(8));
                cpsUsers.setCreateTime(new Date());
                cpsUsers.setNickName("会员" + RandomUtil.randomStringUpper(6));
                cpsUsers.setSource(saSystem.getSource());
                if (saSystem.getSource() == 1) {
                    //客户端
                    cpsUsers.setAvatarUrl("https://ysy.oss-cn-beijing.aliyuncs.com/20230927/UULJEMxnY4C208aa6e1a77dbc98341833b3f422eecc8.png");
                } else if (saSystem.getSource() == 2) {
                    //驻场端
                    cpsUsers.setAvatarUrl("https://ysy.oss-cn-beijing.aliyuncs.com/20230927/u48kz4Wgas8p9a138dd5c8df058f4466729193f8e0e6.png");
                } else if (saSystem.getSource() == 3) {
                    //司机端
                    cpsUsers.setAvatarUrl("https://ysy.oss-cn-beijing.aliyuncs.com/20230927/NqwjSoKKYOX8a5774ad6246a098876c810a56f68f583.png");
                }
//                cpsUsers.setCity("石家庄市");
//                cpsUsers.setProvince("河北省");
//                cpsUsers.setArea("新华区");
                int registerFlag = wxLoginMapper.insert(cpsUsers);
                if (registerFlag > 0) {
                    result.setCode(200);
                    result.setMessage("新用户注册");
                    //通过openId查询用户信息
                    userStorage = wxLoginMapper.getCpsUsersByOpenId(cpsUsers.getOpenid());
                }
            } else {
                //通过openId查询用户信息
                userStorage = wxLoginMapper.getCpsUsersByOpenId(cpsUsers.getOpenid());

                if (userStorage.getDelFlag() == 1) {
                    result.setMessage("账号已封禁");
                    result.setCode(400);
                    result.setSuccess(false);
                    return result;
                }

                cpsUsers.setSuperiorCode(userStorage.getSuperiorCode());
                wxLoginMapper.updateById(cpsUsers);
                result.setMessage("老用户");
                result.setCode(200);
            }
            result.setResult(userStorage);
            return result;
        } catch (Exception e) {
            result.setMessage("服务器响应失败");
            result.setCode(400);
            result.setSuccess(false);
            log.error(e.getMessage(), e);
            return result;
        }
    }

    @Override
    public Result<YsyUsers> getCpsUsersByOpenId(String openId) {
        Result<YsyUsers> result = new Result<>();
        try {
            YsyUsers cpsUsers = wxLoginMapper.getCpsUsersByOpenId(openId);
            result.setResult(cpsUsers);
            result.setCode(200);
            result.setSuccess(true);
            return result;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setMessage("服务器响应失败");
            result.setCode(400);
            result.setSuccess(false);
            return result;
        }
    }

    @Override
    @Transactional
    public Result<YsyUsers> getUserPhone(UsersPhoneQuery usersPhoneQuery) {
        Result<YsyUsers> result = new Result<YsyUsers>();
        try {
            //查询小程序配置
            YsySystem saSystem = wxLoginMapper.getBSystem(usersPhoneQuery.getAppId());
            if (ObjectUtil.isNull(saSystem)) {
                result.setCode(500);
                result.setSuccess(false);
                result.setMessage("小程序配置未找到");
                return result;
            }
            String getAccessToken_URI = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
                    + saSystem.getAppid() + "&secret=" + saSystem.getAppsecret();
            JSONObject getAccessToken = restTemplate.getForObject(getAccessToken_URI, JSONObject.class);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", usersPhoneQuery.getCode());
            ResponseEntity<BinfPhoneNumber> getPhone = restTemplate.postForEntity(getPhoneNumber_URI +
                    getAccessToken.get("access_token"), jsonObject, BinfPhoneNumber.class);
            System.out.println(getPhone.getBody());
            if (getPhone.getBody().getErrcode() != 0) {
                return result.error500("获取手机号错误");
            }
            String phone = getPhone.getBody().getPhone_info().get("phoneNumber").toString();
            YsyUsers saUsers = wxLoginMapper.getFmUserByopenid(usersPhoneQuery.getOpenId());
            if (ObjectUtil.isNotNull(saUsers)) {
                //修改这个手机号
                saUsers.setPhone(phone);
                saUsers.setNickName("会员" + phone);
                wxLoginMapper.updatePhoneByopenid(saUsers);
                result.setResult(saUsers);
                result.setCode(200);
                result.setSuccess(true);
                return result;
            } else {
                result.setMessage("手机号获取失败");
                result.setCode(500);
                result.setSuccess(false);
                return result;
            }

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setMessage("服务器响应失败");
            result.setCode(200);
            result.setSuccess(true);
            return result;
        }
    }

    @Override
    public Result<PageInfo<YsyUsers>> getUserList(Map<String, Object> map) {
        Result<PageInfo<YsyUsers>> result = new Result<>();
        try {
            if (map.get("pageNo") == null || map.get("pageSize") == null) {
                result.setCode(500);
                result.setSuccess(false);
                result.setMessage("参数错误");
                return result;
            }
            PageHelper.startPage(Integer.parseInt(map.get("pageNo").toString()), Integer.parseInt(map.get("pageSize").toString()));
            List<YsyUsers> saPtOrders = wxLoginMapper.getUserList(map);
            PageInfo pageInfo = new PageInfo(saPtOrders);
            result.setCode(200);
            result.setSuccess(true);
            result.setResult(pageInfo);
            return result;
        } catch (Exception e) {
            result.setCode(500);
            result.setSuccess(false);
            result.setMessage("服务器响应失败");
            return result;
        }
    }

    @Override
    @Transactional
    public Result<?> updateUser(YsyUsers saUsers) {
        return Result.ok(wxLoginMapper.updateUser(saUsers));
    }
}
